package server;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.SQLException;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.net.httpserver.HttpServer;

import utilities.Logger;
import utilities.Logger.LoggerLevel;

import persistence.DatabaseManager;


public class Main {

	public static void main(String[] args) {
		final Logger log = Logger.getLogger(Main.class);
		
		Logger.setLoggerLevel(LoggerLevel.DEBUG);
		
		boolean doAuth = true;
		String ipms = "Please pass me \"true\" or \"false\", whether you want to enable http-auth or not.";
		if (args.length == 1) {
			  if (args[0].equals("true")) {
				  doAuth = true;
				  log.plain("AUTH ACTIVATED");
			  } else if (args[0].equals("false")) {
				  doAuth = false;
				  log.plain("AUTH DEACTIVATED");
			  } else {
				  log.plain(ipms);
				  System.exit(0);
			  }
		} else {
			log.plain(ipms);
			System.exit(0);
		}

		log.plain("##############################################");
		log.plain("# Welcome to MCHCSS13 - Group 2 REST Server! #");
		log.plain("##############################################");
		log.plain("");
		
		try {
			
			//DATABASE --------------------------------------------------------------------
			final DatabaseManager dbm = DatabaseManager.getInstance();
			dbm.openConnection("jdbc:hsqldb:hsql://localhost/mchctest","sa","");

			//REST ------------------------------------------------------------------------
			HttpServer server = null;
			if (doAuth) {
				ResourceConfig rc = new PackagesResourceConfig("");
				rc.getProperties().put(
				    "com.sun.jersey.spi.container.ContainerRequestFilters",
				    "com.sun.jersey.api.container.filter.LoggingFilter;server.RestAuth"
				);
				server = HttpServerFactory.create("http://localhost:30102/restApi",rc);
			} else {
				server = HttpServerFactory.create("http://localhost:30102/restApi");
			}
			
			log.i("Starting REST server ...");
			server.start();
			log.i("HTTP server started on: " + server.getAddress().toString());
			log.plain("\nAll Systems up! Press enter to shutdown.");
			
			//WAIT ------------------------------------------------------------------------
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			br.readLine();
			
			//END -------------------------------------------------------------------------
			dbm.closeConnection();
			log.i("Stopping REST server ...");
			server.stop(0);
			log.i("REST server stopped.");
			log.i("Shutting down ...");
			System.exit(0);
		} catch (SQLException e) {
			log.e("Database Error: " + e.getMessage());
		} catch (Exception e) {
			log.e("Something went terribly wrong: " + e.getMessage());
			e.printStackTrace();
		}

	}

}
